package cn.com.self.apis.controller;


import cn.com.self.apis.files.entity.Files;
import cn.com.self.apis.files.service.IFilesService;
import cn.com.self.apis.portal.util.DateUtils;
import cn.com.self.apis.portal.util.ICustomPage;
import cn.com.self.apis.portal.util.StringUtils;
import cn.com.self.apis.util.CopyUtils;
import cn.com.selfsoft.smartcity.commons.http.DataItem;
import cn.com.selfsoft.smartcity.commons.http.DataPage;
import cn.com.selfsoft.smartcity.commons.http.ResultModel;
import cn.com.selfsoft.smartcity.commons.util.ParameterUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 文件管理器
 * </p>
 *
 * @author shisonghua
 * @since 2020-05-29
 */
@RestController
@RequestMapping("/files")
@Api(tags = "文件信息类")
public class FilesController {
    @Autowired
    private IFilesService filesService;

    /**
     * 新增文件
     *
     * @return
     * @Description //TODO
     **/
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ApiOperation(value = "新增文件")
    public ResponseEntity create(@RequestBody Files entity, HttpServletRequest request) {
        entity.setCreateDate(new Date());
        Files create = filesService.create(entity);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(create));
    }


    /**
     * 分页获取托文件列表
     *
     * @return
     * @Description //TODO
     **/
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取托文件列表")
    public ResponseEntity getFilesPage(HttpServletRequest request, Pageable page) {
        Map<String, Object> queryParams = ParameterUtil.HumpToUnderline(request.getParameterMap(), "mark", "size", "page", "sort","access_token");
        ICustomPage<Files> pageData = this.filesService.page(queryParams, page);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(pageData));

    }

    /**
     * 获取单个文件信息
     *
     * @return
     * @Description //TODO
     **/
    @ApiOperation(value = "获取单个文件信息")
    @RequestMapping(value = {"/load/{id}"}, method = RequestMethod.GET)
    public ResponseEntity loadFiles(@PathVariable("id") String id, HttpServletRequest request) {
        Files files = this.filesService.load(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(new DataItem(files)));

    }


    /**
     * 修改文件信息
     *
     * @return
     * @Description //TODO
     **/
    @ApiOperation(value = "修改文件信息")
    @RequestMapping(value = {"/update/{id}"}, method = RequestMethod.POST)
    public ResponseEntity update(@PathVariable("id") String id, @RequestBody Files entity, HttpServletRequest request) {
        Files files = this.filesService.load(id);
        CopyUtils.copyProperties(entity, files);
        Files update = this.filesService.update(files);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(new DataItem(update)));

    }


    /**
     * 删除文件信息
     *
     * @return
     * @Description //TODO
     **/
    @ApiOperation(value = "删除文件信息")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public ResponseEntity deletes(@PathVariable("id") String id) {
        this.filesService.delete(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResultModel<>(1));
    }

    //文件上传接口
    @ApiOperation(value = "文件上传接口")
    @ResponseBody
    @RequestMapping(value = {"/upLoadFile"}, method = RequestMethod.POST)
    public Map upLoad(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        Map map = new HashMap<>();
        try {
            long size = file.getSize();//文件大小，字节,90.2 KB (92,422 字节)
            String filesize;
            double size2;
            if (size / (1024 * 1024 * 1024) > 1) {//单位G
                size2 = new BigDecimal((float) size / (1024 * 1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "G";
            } else if (size / (1024 * 1024) > 1) {//单位M
                size2 = new BigDecimal((float) size / (1024 * 1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "M";
            } else {//单位KB
                size2 = new BigDecimal((float) size / (1024)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                filesize = size2 + "KB";
            }
            String timeurl = DateUtils.getYear() + "/" + DateUtils.getMonth() + "/" + DateUtils.getDay();
            String date = DateUtils.getDateString(new Date());
            //文件名
            String filename = file.getOriginalFilename();
            String[] name = filename.split("\\.");
            //文件扩展名
            String suffix = name[name.length - 1];
            //文件类型
            String filetype = request.getParameter("filetype");

            String filename2 = System.currentTimeMillis() + "_" + new Random().nextInt(9999) + "." + name[name.length - 1];
            String savePath = request.getParameter("uploadPath");
            String uploadPath = "/uploadFiles";
            if (StringUtils.isNotBlank(savePath)) {
                uploadPath += "/" + savePath + "/" + timeurl + "/";
            } else {
                uploadPath += "/files/" + timeurl + "/";
            }
//            String uploadPath2 = request.getRealPath(uploadPath) + File.separator;
            String uploadPath2 = request.getSession().getServletContext().getRealPath(uploadPath) + File.separator;

            File newFile = new File(uploadPath2, filename2);
            //判断路径是否存在，如果不存在就创建一个
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            file.transferTo(newFile);
            String filepath = uploadPath + filename2;//保留文件本地路径

            System.out.println(filepath);

            map.put("filename", filename);
            map.put("filename2", filename2);
            map.put("filePath", filepath);
            map.put("fileId", "");
            map.put("filesize", filesize);
            map.put("suffix", suffix);
            map.put("filetype", filetype == null ? "0" : filetype);

            //保存文件信息到数据库
            filesService.saveFile(map);

            map.put("success", true);
        } catch (Exception e) {
            System.err.println(e);
            map.put("success", false);

        }
        return map;
    }

}

